package org.fao.pims.persistence;
/*
 * Copyright 1999-2004 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.DriverManager;
import org.apache.commons.dbcp.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.pool.*;
import org.apache.commons.pool.impl.*;
import org.apache.commons.dbcp.BasicDataSource;


public class MyBasicDataSource {
    
    /** Logger */
	private static Log log = LogFactory.getLog(MyBasicDataSource.class);
	
	private static String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
	private static String MYSQL_DB_USER_NAME = "pims_user";
	//private static String MYSQL_DB_USER_NAME = "root";
	private static String MYSQL_DB_USER_PASSWORD = "pims";
	//private static String MYSQL_DB_USER_PASSWORD = "password";
	private static String MYSQL_DB_URL = "jdbc:mysql://ltsdbwm1.fao.org:3330/pims";
	//private static String MYSQL_DB_URL = "jdbc:mysql://localhost:3306/pims";
	private static int DATASOURCE_MAX_ACTIVE = 10;
	private static int DATASOURCE_MAX_WAIT = 100;
	private static boolean DATASOURCE_AUTOCOMMIT = true;
	private static boolean DATASOURCE_DEFAULT_READ_ONLY = false;
	
	BasicDataSource bds = null;
    Connection conn = null;
    
    public DataSource setup() {
        
        
        bds = new BasicDataSource();
        bds.setDriverClassName(MYSQL_DRIVER);
        bds.setUsername(MYSQL_DB_USER_NAME);
        bds.setPassword(MYSQL_DB_USER_PASSWORD);
        bds.setUrl(MYSQL_DB_URL);
        bds.setMaxActive(DATASOURCE_MAX_ACTIVE);
        bds.setMaxWait(DATASOURCE_MAX_WAIT);
        bds.setDefaultAutoCommit(DATASOURCE_AUTOCOMMIT);
        bds.setDefaultReadOnly(DATASOURCE_DEFAULT_READ_ONLY);
        // remove idle connections and log
        /*
        bds.setRemoveAbandoned(true);
        bds.setRemoveAbandonedTimeout(60);
        bds.setLogAbandoned(true);
        */
        
        return bds;
    }
    
    public Connection getConnection()
    {
        
       try {
        Class.forName(MYSQL_DRIVER);
       
        // inizializza il pooling driver
        ObjectPool connPool = new GenericObjectPool(null);
        DriverManagerConnectionFactory connFactory;
        connFactory = new DriverManagerConnectionFactory(MYSQL_DB_URL,
                                                         MYSQL_DB_USER_NAME,
                                                         MYSQL_DB_USER_PASSWORD);
        PoolableConnectionFactory poolConnFactory;
        poolConnFactory = new PoolableConnectionFactory(connFactory, connPool, null, null, false, true);
        PoolingDriver driver = new PoolingDriver();
        driver.registerPool("mypool", connPool);
        
        conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:mypool");
        
        conn.setAutoCommit(DATASOURCE_AUTOCOMMIT);
        
        
        log.info("Connect to the pool: mypool");
            
        }
        catch (Exception sqle) {
            //System.out.println("Errore connessione.");
            //sqle.printStackTrace();
            log.error("Cannot connect to the database pool, url: " + MYSQL_DB_URL);
        }
        
        return conn;
    }
    
    public void closeConnection() {
    	
    	if (conn != null) {
    		try {
    		
    			conn.close();
    			
    		}
    		catch(Exception e) {
    			
    			log.error(e.getMessage());
    			
    		}
    		
    	}
    	
    }
    
    
}
